<?php

namespace app\common\model\diy;

use tmcore\base\BaseModel;
use tmcore\traits\ModelTrait;
use app\common\cache\DiyCache;

/**
 * 页面装修模型
 */
class Diy extends BaseModel
{
    use ModelTrait;

    /**
     * 获取参数
     * @param $value
     * @return string
     */
    public function getDataAttr($value)
    {
        return empty($value) ? '' : json_decode($value, true);
    }

    /**
     * 获取diy缓存key
     * @param $type
     * @param $name
     * @return string
     */
    public function getDiyCacheKey($type, $name) {
        return ($type == 1?'app':"pc") . '_' . $name;
    }

    /**
     * 设置diy缓存
     * @param $type
     * @param $name
     * @param $data
     */
    public function setDiyCache($type, $name, $data) {
        $key = $this->getDiyCacheKey($type, $name);
        (new DiyCache)->setDiyData($key, $data);
    }

    /**
     * 设置diy缓存
     * @param $type
     * @param $name
     * @return array|mixed
     */
    public function getDiyCache($type, $name) {
        $key = $this->getDiyCacheKey($type, $name);
        $cache = (new DiyCache)->getDiyData($key);
        if($cache) {
           return $cache && is_string($cache) ? json_decode($cache, true):($cache??[]);
        } else {
            $data = Diy::where(['name' => $name, 'type' => $type])->value('data');
            (new DiyCache)->setDiyData($key, $data);
            return $data;
        }
    }
}